#include <iostream>
#include <vector>

using namespace std;
class Solution
{
public:
    int orangesRotting(vector<vector<int>> &grid)
    {
        vector<vector<int>> dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        int goodCount = 0;
        int lastCount = -1;
        for (int i = 0; i < grid.size(); i++)
        {
            for (int j = 0; j < grid[0].size(); j++)
            {
                if (grid[i][j] == 1)
                    goodCount++;
            }
        }
        int loop = 5;
        while (true)
        {
            if (goodCount == 0)
                return loop - 5;
            if (lastCount == goodCount)
                return -1;
            lastCount = goodCount;
            for (int i = 0; i < grid.size(); i++)
            {
                for (int j = 0; j < grid[0].size(); j++)
                {
                    if (grid[i][j] > 1 && grid[i][j] < loop)
                    {
                        for (int k = 0; k < dir.size(); k++)
                        {
                            int x = i + dir[k][0];
                            int y = j + dir[k][1];
                            if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == 1)
                            {
                                grid[x][y] = loop;
                                goodCount--;
                            }
                        }
                    }
                }
            }
            loop++;
        }
    }
};

int main()
{
    cout << "Code994" << endl;
    Solution s;
    //[[2,1,1],[1,1,0],[0,1,1]]
    vector<vector<int>> grid = {{2, 1, 1}, {1, 1, 0}, {0, 1, 1}};
    cout << s.orangesRotting(grid) << endl;
    return 0;
}